﻿
using System;

namespace VASJ.Model
{
    public class DataContextOwner : IDisposable
    {
        protected KeToanDataContext m_DataContext = null;
        protected bool m_HasDataContext = false;

        public KeToanDataContext DataContext
        {
            get
            {
                return m_DataContext;
            }
        }

        protected DataContextOwner()
        {
            try
            {
                m_DataContext = DataContextFactory.CreateDataContext();
                m_HasDataContext = true;
            }
            catch (Exception ex)
            {
                Logger.Log.Fatal("Unable to initial the data context");
                Logger.Log.Fatal(ex.Message);
                throw ex;
            }
        }

        protected DataContextOwner(KeToanDataContext context)
        {
            m_HasDataContext = false;
            m_DataContext = context;
        }

        #region Dispose

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (m_HasDataContext)
                    {
                        m_DataContext.Dispose();
                        m_DataContext = null;
                    }
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion Dispose
    }
}